package com.zhengbing.tj.common;

import com.zhengbing.tj.entity.User;
import javax.servlet.http.HttpServletRequest;
import com.zhengbing.tj.utils.JwtUtils;
import com.zhengbing.tj.service.UserService;

/**
 * 用户上下文工具类
 * 使用ThreadLocal存储当前线程的用户信息，实现请求线程内用户数据的共享
 * 提供从请求中提取用户信息并设置到上下文、获取当前用户、清理上下文等静态方法
 * 
 * @author zhengbing
 * @date 2025-07-29
 */
public class UserContext {
    private static final ThreadLocal<User> USER_THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 设置当前用户到ThreadLocal
     * 将用户信息存储到当前线程的ThreadLocal中，确保线程内用户数据隔离
     * 
     * @param user 当前登录用户实体对象
     */
    public static void setUser(User user) {
        USER_THREAD_LOCAL.set(user);
    }

    /**
     * 从ThreadLocal获取当前用户
     * 获取当前线程中存储的用户信息，如果未设置则返回null
     * 
     * @return 当前登录用户实体对象，如果未设置返回null
     */
    public static User getUser() {
        return USER_THREAD_LOCAL.get();
    }

    /**
     * 清除ThreadLocal中的用户信息
     * 请求处理完成后清理ThreadLocal，防止内存泄漏和用户信息跨请求污染
     */
    public static void clear() {
        USER_THREAD_LOCAL.remove();
    }

    /**
     * 从请求头提取token并解析用户信息
     * 从HTTP请求的Authorization头中提取JWT token，解析后获取对应的用户实体
     * 
     * @param request HTTP请求对象
     * @return 解析得到的用户实体对象
     * @throws IllegalArgumentException token无效或用户不存在时抛出
     * @throws IllegalStateException Spring上下文工具未初始化时抛出
     */
    public static User getUserFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new IllegalArgumentException("无效的token");
        }
        String token = authHeader.replace("Bearer ", "");
        JwtUtils jwtUtils = SpringContextUtil.getBean(JwtUtils.class);
        if (jwtUtils == null) {
            throw new IllegalStateException("JwtUtils bean not found in Spring context");
        }
        String username = jwtUtils.getUsernameFromToken(token);
        if (username == null || username.isEmpty()) {
            throw new IllegalArgumentException("Invalid token: username cannot be empty");
        }
        UserService userService = SpringContextUtil.getBean(UserService.class);
        if (userService == null) {
            throw new IllegalStateException("UserService bean not found in Spring context");
        }
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new IllegalArgumentException("User not found with username: " + username);
        }
        return user;
    }
}